#include <QDebug>
#include <QThread>
#include "application.h"
#include "portmanager.h"
#include "modulemanager.h"
#include "configmanager.h"

SINGLETON_IMPLIMENT(Application)

Application::Application(QObject *parent)
    : QObject(parent)
{

}

void Application::start()
{
    qDebug() << "Application start...";

    /*******************************************************************
     * config init
     *******************************************************************/
    configManager;
    QThread *th = new QThread();
    configManager->moveToThread(th);
    th->setObjectName("config_manager_thread");
    connect(th, &QThread::started, configManager, &ConfigManager::onStart);
    connect(th, &QThread::finished, this, [=] () {
        th->deleteLater();
    });
    th->start();

    /*******************************************************************
     * port init
     *******************************************************************/
    portManager;
    th = new QThread();
    portManager->moveToThread(th);
    th->setObjectName("port_manager_thread");
    connect(th, &QThread::started, portManager, &PortManager::onStart);
    connect(th, &QThread::finished, this, [=] () {
        th->deleteLater();
    });
    // 即使这里start了线程，实际还是需要到大循环后,线程才会真正启动（至少started信号是）
    th->start();

    /*******************************************************************
     * module init
     *******************************************************************/
    moduleManager;
    th = new QThread();
    moduleManager->moveToThread(th);
    th->setObjectName("module_manager_thread");
    // port启动完成后才初始化module
    connect(portManager, &PortManager::started, moduleManager, &ModuleManager::onStart);
    connect(th, &QThread::finished, this, [=] () {
        th->deleteLater();
    });
    th->start();

    qDebug() << "Application start...completed";
}

void Application::publish(QEvent* event)
{
    m_messageQueue.publish(event);
}

void Application::publish(QObject *obj, QEvent* event)
{
    m_messageQueue.publish(obj, event);
}

void Application::subscribe(quint16 id, QObject* who)
{
    m_messageQueue.subscribe(id, who);
}

void Application::unsubscribe(quint16 id, QObject *who)
{
    m_messageQueue.unsubscribe(id, who);
}
